package com.gdk.ksoft.assembly.service;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.receiver.LocationReceiver;
import com.gdk.ksoft.assembly.receiver.UploadNotifyReciever;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.TaskUtils;
import com.lidroid.xutils.DbUtils;

/**
 * Created by hel on 2014-11-20.
 * 地理位置Service
 */
public class LocationService extends Service implements BDLocationListener{

    private Thread uploadThread = null;

    /**
     * 线程是否可以运行的标志
     */
    private boolean flag = false;

    /**
     * 上传数据的消息通知
     */
    private UploadNotifyReciever uploadNotifyReciever;

    /**
     * 注册消息通知
     */
    public void registeReceiver(){
        uploadNotifyReciever = new UploadNotifyReciever(new UploadNotifyReciever.OnUploadStateChangedListener() {
            @Override
            public void onUploadStateChanged(boolean isOpenUpload) {
//                openOrStopUpload(isOpenUpload);//开启或者停止上传数据
            }
        });
        IntentFilter filter = new IntentFilter(UploadNotifyReciever.ACTION);
        this.registerReceiver(uploadNotifyReciever,filter);
    }

    /**
     * 开启或者停止上传数据
     * @param isOpenUpload
     */
    public void openOrStopUpload(boolean isOpenUpload){
        if(isOpenUpload) {
            try {
                if (flag) return;//当前任务已经在运行了，不需要再运行
                flag = true;//允许后台运行上传线程
                recordeSaleManLatLng();//隔一段时间记录一次业务员的经纬度值
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try{
                if(!flag) return;//当前任务已经停止，不需要再执行停止
                flag = false;
                if(uploadThread!=null){//终止线程运行
                    uploadThread.interrupt();
                    uploadThread = null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化定位函数
     */
    public void initLoc(){
        System.out.println("-----> 开始运行地理位置服务...");
        LocationClientOption locOption = new LocationClientOption();
        locOption.setCoorType("bd09ll");
        locOption.setIsNeedAddress(true);
        locOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        locOption.setNeedDeviceDirect(true);
        locOption.setOpenGps(true);
        locOption.setScanSpan(3000);
        locOption.setTimeOut(10*1000);
        LocationClient locClient = new LocationClient(this,locOption);
        locClient.registerLocationListener(this);
        locClient.requestLocation();//请求位置
        locClient.start();//开始定位
    }

    /**
     * 记录业务员的经纬度
     */
    public void recordeSaleManLatLng(){
        uploadThread = new Thread(new Runnable(){
            @Override
            public void run() {
                while(flag) {
                    try{
                        Thread.sleep(SystemData.TimeToRecorder*1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    final DbUtils dbUtils = SQLiteUtils.getInstance(LocationService.this).getDbUtils();
                    try {
                        TaskUtils.saveLatlngToLocation(dbUtils);//储存经纬度数据到本地
                        TaskUtils.uploadLatlng(LocationService.this, dbUtils);//上传经纬度数据到服务器
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        uploadThread.start();//开启线程
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("执行了OnStart方法");
        initLoc();//初始化地图定位函数
        registeReceiver();//注册上传通知
        return Service.START_STICKY;
    }

    @Override
    public void onReceiveLocation(BDLocation loc) {
        final double errorLoc = 4.9E-324;//错误的经纬度值，不能定位当前位置
        if(loc != null && loc.getLongitude()>errorLoc && loc.getLatitude()>errorLoc){
            SystemData.currentLocation = loc;//获取当前的经纬度
            Intent intent = new Intent(LocationReceiver.ACTION_RECIEVER);
            intent.putExtra("location",loc);
            sendBroadcast(intent);
        }
    }

    @Override
    public void onDestroy() {
        flag = false;//停止线程运行
        if(uploadNotifyReciever!=null)
            this.unregisterReceiver(uploadNotifyReciever);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


}
